#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <device.h>

#ifdef __CBM__
#include <cbm.h>
#endif

#include "Global.h"
#include "Users.h"
#include "OverlayManagement.h"
#include "BbsControlData.h"
#include "Waiting.h"
#include "conio.h"
#include "Session.h"

bbsControlData_t bcd;
connect_states_t _connectState;
time_t _baseTime = 0;

extern void _ML_LOAD__, _ML_SIZE__;


void main(void)
{
	static FILE *file;
	static char oldDirectory[17];
	static char directory[17];
	static char filename[17];

	_connectState = CS_DISCONNECTED;


	bgcolor(COLOR_BLACK);
	bordercolor(COLOR_BLACK);

	initUser();

	memset(&bcd, 0, sizeof(bbsControlData_t));

#ifndef __NODCD__
	bcd.bbsDirectory.device = 8;
	bcd.dataDirectory.device = 9;
	bcd.mailDirectory.device = 9;
	bcd.usersDirectory.device = 9;
#else
	bcd.bbsDirectory.device = 8;
	bcd.dataDirectory.device = 8;
	bcd.mailDirectory.device = 8;
	bcd.usersDirectory.device = 8;
#endif

	//puts("BridgeBBS Kernal Loaded.\r\n");
	memset(&filename, 0, 17);
#ifdef __CBM__
#ifdef __C64__
	strcpy(filename, "rs232-c64.ml");
#else
	strcpy(filename, "rs232-c128.ml");
#endif

	getcwd(oldDirectory, 17);
	getdevicedir(bcd.bbsDirectory.device, directory, 17);
	chdir(directory);

	file = fopen(filename, "rb");

	if(file != NULL)
	{
		fread(&_ML_LOAD__, 2, 1, file);
		if(fread(&_ML_LOAD__, 1, (unsigned)&_ML_SIZE__, file) != (unsigned)&_ML_SIZE__)
		{
			fclose(file);
			puts("Failed to load CBM serial driver.");
			return;
		}
		fclose(file);
	}
	else
	{
		puts("filename: "); puts(filename);
		puts("directory: "); puts(directory);
		puts("Failed to load CBM serial driver.");
		return;
	}
#endif
	//puts("RS232 Driver Loaded.\r\nLoading Wait Module.");

	clrscr();

	if(loadOverlay("bbs.wait", &waitForCall, "bbs.wait") > 0)
	{
	}
	else
	{
		puts("Failed to load bbs wait overlay.");
	}
}

